using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;
public partial class GonzalesAdminApproverReplacment : System.Web.UI.Page
{

    #region Variables

    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;

    #region SavedSuccessMessage
    protected string SavedSuccessMessage
    {
        get
        {
            return ViewState["SavedSuccessMessage"].ToString();
        }

        set
        {
            ViewState["SavedSuccessMessage"] = value;
        }
    }
    #endregion

    #region SavedFailedMessage
    protected string SavedFailedMessage
    {
        get
        {
            return ViewState["SavedFailedMessage"].ToString();
        }

        set
        {
            ViewState["SavedFailedMessage"] = value;
        }
    }
    #endregion

    #region MissingCurAppMessage
    protected string MissingCurAppMessage
    {
        get
        {
            return ViewState["MissingCurAppMessage"].ToString();
        }

        set
        {
            ViewState["MissingCurAppMessage"] = value;
        }
    }
     #endregion

    #region MissingNewAppMessage
    protected string MissingNewAppMessage
    {
        get
        {
            return ViewState["MissingNewAppMessage"].ToString();
        }

        set
        {
            ViewState["MissingNewAppMessage"] = value;
        }
    }
      #endregion

    #region MissingReasonMessage
    protected string MissingReasonMessage
    {
        get
        {
            return ViewState["MissingReasonMessage"].ToString();
        }

        set
        {
            ViewState["MissingReasonMessage"] = value;
        }
    }
    #endregion

    #region SameApproverMessage
    protected string SameApproverMessage
    {
        get
        {
            return ViewState["SameApproverMessage"].ToString();
        }

        set
        {
            ViewState["SameApproverMessage"] = value;
        }
    }
      #endregion

    #region DuplicateExpenseDetailAppr
    protected string DuplicateExpenseDetailAppr
    {
        get
        {
            return ViewState["DuplicateExpenseDetailAppr"].ToString();
        }

        set
        {
            ViewState["DuplicateExpenseDetailAppr"] = value;
        }
    }
    #endregion

    #endregion

    #region Event
    protected void Page_Load(object sender, EventArgs e)
    {

        this.SessionCheck();

        if (!IsPostBack)
        {
           
            this.SwitchLanguage();
            this.PageComponentSetup();
 
        } 
    }
    #region DropDownList_ByEntity_SelectedIndexChanged
    protected void DropDownList_ByEntity_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (CompanyManager CurCompanyManager = new CompanyManager(this.CurrentPrivateSession))
        {
            GonzalesCompanies ResultList = CurCompanyManager.GetCompanyByEntityID(this.DropDownList_ByEntity.SelectedValue);

            if (ResultList != null)
            {
                this.DropDownList_ByCompany.Items.Clear();
                this.DropDownList_ByCompany.Items.Add(new ListItem("", ""));

                for (int x = 0; x < ResultList.Count; x++)
                {
                    this.DropDownList_ByCompany.Items.Add(new ListItem(ResultList[x].CompanyName, ResultList[x].InternalID));
                }
            }
            else
            {
                this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.DropDownList_ByEntity_SelectedIndexChanged] : Failed on CurCompanyManager.GetCompanyByEntityID('" + this.DropDownList_ByEntity.SelectedValue + "') : " + CurCompanyManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            }

            if (this.DropDownList_ByEntity.SelectedValue == this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.FromCountry.InternalID)
                this.DropDownList_ByCompany.Items.FindByValue(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.InternalID).Selected = true;
        }

        #region Filter the company by Finance Admin
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinanceAdmin)
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                GonzalesCompanies ResultCompanies = CurUserManager.GetCompanyByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultCompanies != null)
                {
                    int x = 0;

                    while (x < this.DropDownList_ByCompany.Items.Count)
                    {
                        bool Matched = false;

                        for (int y = 0; y < ResultCompanies.Count; y++)
                        {
                            if (ResultCompanies[y].InternalID.CompareTo(this.DropDownList_ByCompany.Items[x].Value) == 0)
                            {
                                Matched = true;
                                break;
                            }
                        }

                        if (!Matched)
                        {
                            this.DropDownList_ByCompany.Items.RemoveAt(x);
                        }
                        else
                        {
                            x++;
                        }
                    }
                }
            }
        }
        #endregion

    }
    #endregion
  
   
    protected void ImageButton_Cancel_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("GonzalesAdminMain.aspx");
    }

    protected void Button_Submit_Click(object sender, EventArgs e)
    {
        bool smooth = true;
        int totalPendingClaim = 0;
        int totalAppMatrix = 0;
        string msg ="";
        if (this.HiddenField_curApp.Value.Length == 0)
        {
            smooth = false;
            this.ShowErrorMessage(this.MissingCurAppMessage);            
        }
        if (smooth)
        {
            if (this.HiddenField_PersonnelInternalID.Value.Length == 0)
            {
                smooth = false;
                this.ShowErrorMessage(this.MissingNewAppMessage);
            }
        }
        if (smooth)
        {
            if (this.TextBox_Reason.Text.Length == 0)
            {
                smooth = false;
                this.ShowErrorMessage(this.MissingReasonMessage);
            }
        }
        if (smooth)
        {
            if (this.HiddenField_curApp.Value.Equals(this.HiddenField_PersonnelInternalID.Value) )
            {
                smooth = false;
                this.ShowErrorMessage(this.SameApproverMessage);
            }
        }
        if (smooth)
        {

        }
        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
        {
            using (UserManager userManager = new UserManager(this.CurrentPrivateSession))
            {
               
                if (smooth)
                {
                    #region update matrix table
                    DataTable Result = userManager.GetExceptionalApproversMatrixByEntity(this.HiddenField_curApp.Value, DropDownList_ByCompany.SelectedValue);

                   
                    if (Result != null)
                    {
                        #region check duplicate approver detail
                        foreach (DataRow ResultRow in Result.Rows)
                        {
                            string user_id = ResultRow["user_id"].ToString();
                            SystemUsers ApproversList = userManager.GetExceptionalApproversMatrix(user_id);
                            if (ApproversList != null)
                            {
                                for (int x = 0; x < ApproversList.Count; x++)
                                {
                                    if (ApproversList[x].InternalID.CompareTo(this.HiddenField_PersonnelInternalID.Value) == 0)
                                    {
                                        smooth = false;
                                         SystemUser claimant = null;
                                         claimant = userManager.GetUserByInternalID(ResultRow["user_id"].ToString());
                                         this.ShowErrorMessage(this.DuplicateExpenseDetailAppr + " Claimant Name: " + claimant.DisplayName );
                                        break;
                                    }
                                }
                            }
                        }
                        #endregion

                        if (smooth)
                        {
                            foreach (DataRow ResultRow in Result.Rows)
                            {
                                string user_id = ResultRow["user_id"].ToString();
                                SystemUser claimant = null;
                                SystemUser Approver = null;
                                SystemUser NewApp = null;
                                claimant = userManager.GetUserByInternalID(ResultRow["user_id"].ToString());
                                Approver = userManager.GetUserByInternalID(ResultRow["approver_id"].ToString());
                                NewApp = userManager.GetUserByInternalID(this.HiddenField_PersonnelInternalID.Value);

                                if (!userManager.EditExceptionalApprover(user_id, Approver.InternalID,
                                this.HiddenField_PersonnelInternalID.Value))
                                {
                                    this.ShowErrorMessage(this.SavedFailedMessage);
                                    this.CurLogManager.LogError("[GonzalesAdminApproverReplacmen.Button_Submit_Click] : Failed at userManager.EditExceptionalApprover() : " + userManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                }
                                else
                                {
                                    totalAppMatrix = totalAppMatrix + 1;
                                    //log the action
                                    this.CurLogManager.LogMessage("[GonzalesAdminApproverReplacmen.Button_Submit_Click] : Edit Exception Approver ("
                                        + Approver.InternalID + ", " + Approver.DisplayName
                                        + ",[old approver] to " + NewApp.InternalID + ", " + NewApp.DisplayName + " ,[new approver]) updated, to Claimant("
                                        + claimant.InternalID + ", " + claimant.DisplayName + ")", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                               msg = msg +claimant.DisplayName + " approver changed from " + Approver.DisplayName + " to " + NewApp.DisplayName + " \\n";
                                }
                            }
                        }
                     }
                    #endregion
                }

                if (smooth)
                {
                    #region check if have pending claim

                    ClaimHeaders ResultObj = CurClaimManager.GetClaimsByApprover(this.HiddenField_curApp.Value, DropDownList_ByCompany.SelectedValue);

                    if (ResultObj != null)
                    {
                        for (int x = 0; x < ResultObj.Count; x++)
                        {
                            GonzalesClaimHeader CurClaimHeader = (GonzalesClaimHeader)ResultObj[x];
                            string claimId = ResultObj[x].ClaimID;

                            SystemUser Approver = null;
                            SystemUser NewApp = null;

                            Approver = userManager.GetUserByInternalID(ResultObj[x].NextApprover.InternalID);
                            NewApp = userManager.GetUserByInternalID(this.HiddenField_PersonnelInternalID.Value);

                            if (!CurClaimManager.UpdateClaimHeaderWhenChangeApprover(ResultObj[x].InternalID, this.HiddenField_PersonnelInternalID.Value))
                            {
                                smooth = false;
                                this.ShowErrorMessage(this.SavedFailedMessage);
                                this.CurLogManager.LogError("[GonzalesAdminApproverReplacment.Button_Submit_Click] : Failed at CurClaimManager.UpdateClaimHeaderWhenChangeApprover() : " + userManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                            }
                            else
                            {
                                //log the action
                                totalPendingClaim = totalPendingClaim + 1;
                                this.CurLogManager.LogMessage("[GonzalesAdminApproverReplacment.Button_Submit_Click] : [GonzalesAdminApproverExceptionChange] :Claim ID:'" + ResultObj[x].ClaimID + "' exception approver from(" + Approver.InternalID + ", " + Approver.DisplayName + "), to (" + NewApp.InternalID + ", " + NewApp.DisplayName + ")changed)", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                            }
                        }
                    }
                    #endregion
                    msg = msg +  "Total updated for pending approver claim: " + totalPendingClaim + " \\nTotal updated for Approver Setting on the exceptional Approver: " + totalAppMatrix;
                    this.ClientScript.RegisterStartupScript(this.GetType(), "Data Saved", "<script language=\"javaScript\">" +
                          "alert('" + msg + "');" + "window.location.href='#';" + "<" + "/script>");
                    this.TextBox_Reason.Text = "";
                }
                this.HiddenField_curApp.Value = "";
                this.HiddenField_PersonnelInternalID.Value = "";
                                               
            }
        }
    }
    protected void Button_Cancel_Click(object sender, EventArgs e)
    {
        this.LabelValue_curApp.Text = "";
        this.HiddenField_curApp.Value = "";
        this.LabelValue_Approver.Text = "";
        this.HiddenField_curApp.Value = "";
        this.Table_MessageBox.Visible = false;
    }
    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {

        // setup entity
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsPowerAdmin)
        {
            #region Power Admin
            using (EntityManager CurEntityManager = new EntityManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurEntityManager.GetAllEntity();
                if (ResultList != null)
                {
                    this.DropDownList_ByEntity.Items.Add(new ListItem("", ""));
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurEntityManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);

                }
            }

            //Added by Agnes [13 Jul 2009] - set the default country.
            this.DropDownList_ByEntity.Items.FindByValue(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.Entity.InternalID).Selected = true;
        
            #endregion
        }
        else
        {
            #region Finance Admin

            using (UserManager CurManager = new UserManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurManager.GetEntityByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultList != null)
                {
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }

            #endregion
        }

        if (Request.QueryString["entity"] != null && Request.QueryString["company"] != null)
        {
            this.DropDownList_ByEntity.SelectedItem.Selected = false;
            this.DropDownList_ByEntity.Items.FindByValue(Request.QueryString["entity"]).Selected = true;

            this.DropDownList_ByEntity_SelectedIndexChanged(null, null);

            this.DropDownList_ByCompany.Items.FindByValue(Request.QueryString["company"]).Selected = true;
        }
        else
        {

            this.DropDownList_ByEntity_SelectedIndexChanged(null, null);
        }
        //cancel button
        this.ImageButton_Cancel.Attributes["onclick"] = "return confirm('All unsaved data will be lost, are you sure?');";
        // browse button
        this.Button_Browse.Attributes["onclick"] = "ShowModal('AddressBook', document.getElementById('ModalResult')); return false;";
        this.Button1.Attributes["onclick"] = "ShowModal('AddressBookCurrentApprover', document.getElementById('ModalResult')); return false;";
      
        this.Button_Submit.Attributes["onclick"] = "return confirm('This change will apply to all pending claim and claimant exceptional approver setting. Do you still want to process?');";
           
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_AddNew.Text = CurLanguageFactory.DisplayValue("Title");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_Entity.Text = CurLanguageFactory.DisplayValue("Entity");
                this.Label_Company.Text = CurLanguageFactory.DisplayValue("Company");
                this.Label_CurApprover.Text = CurLanguageFactory.DisplayValue("CurrentApprover");
                this.Button1.Text = CurLanguageFactory.DisplayValue("Browse");
                this.Label_To.Text = CurLanguageFactory.DisplayValue("To");
                this.Label_Approver.Text = CurLanguageFactory.DisplayValue("NewApprover");
                this.Button_Browse.Text = CurLanguageFactory.DisplayValue("Browse");
                this.Label_Reason.Text = CurLanguageFactory.DisplayValue("Reasons");
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Confirm");
                this.Button_Cancel.Text = CurLanguageFactory.DisplayValue("Cancel");
                this.SavedSuccessMessage = CurLanguageFactory.DisplayValue("SavedSuccessMessage");
                this.SavedFailedMessage = CurLanguageFactory.DisplayValue("SavedFailedMessage");
                this.MissingCurAppMessage = CurLanguageFactory.DisplayValue("MissingCurAppMessage");
                this.MissingNewAppMessage = CurLanguageFactory.DisplayValue("MissingNewAppMessage");
                this.MissingReasonMessage = CurLanguageFactory.DisplayValue("MissingReasonMessage");
                this.SameApproverMessage = CurLanguageFactory.DisplayValue("SameApproverMessage");
                this.DuplicateExpenseDetailAppr = CurLanguageFactory.DisplayValue("DuplicateExpenseDetailAppr");
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesMyClaims.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "ErrorBox";
    }
    #endregion

    #region ShowMessage
    protected void ShowMessage(string Message)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = Message;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "MessageBox";
    }
    #endregion

    #endregion
}
